﻿using MediatR;
using WarehouseManagement.Application.Command.WarehouseTypeCommand;
using WarehouseManagement.Domain.DTO.WarehouseType;
using WarehouseManagement.Domain.Entity;
using WarehouseManagement.Infrstructre.Interface;
namespace WarehouseManagement.Application.CommandHandler.WareTypeCommandHandler
{
    /// <summary>
    /// 仓库分类显示树形
    /// </summary>
    public class SelectWareTypeCommandHandler:IRequestHandler<SelectWareTypeCommand,List<WareTypeSelectDTO>>
    {

        private readonly IWareTypeRepository _repository;


        public SelectWareTypeCommandHandler(IWareTypeRepository repository)
        {
            _repository = repository;
        }

        public async Task<List<WareTypeSelectDTO>> Handle(SelectWareTypeCommand request, CancellationToken cancellationToken)
        {
            List<WarehouseCategory> categories = (await _repository.GetAll()).ToList();
            List<WareTypeSelectDTO> dtos = BuildTree(categories, request.id);
            return dtos;
        }


        // 递归构建分类树
        static List<WareTypeSelectDTO> BuildTree(List<WarehouseCategory> categories,int parentId)
        {
            return categories
               .Where(c => c.WCFatherType == parentId&&c.IsDel==false)
               .Select(c => new WareTypeSelectDTO
               {
                   value = c.WarehouseCategoryId,
                   label = c.WCTypeName,
                   children = BuildTree(categories, c.WarehouseCategoryId) // 递归构建子分类
               })
               .ToList();
        }
    }
}
